<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline head-form">
          <el-form-item v-if="btnFunc.some(btn=>btn=='add')">
            <el-button @click="channelInfo()" size="small" icon="el-icon-plus" type="primary">添加渠道
            </el-button>

          </el-form-item>
        </el-form>
        <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading"
                  :data="channelList" border row-key="id"   @selection-change="handleSelectionChange">
          <el-table-column show-overflow-tooltip type="selection" align="center"/>
          <el-table-column show-overflow-tooltip prop="id" label="ID" align="center" width="80" />
          <el-table-column show-overflow-tooltip prop="name" label="渠道名称" align="center" />
          <el-table-column show-overflow-tooltip prop="status" label="微信数量" align="center" >
            <template slot-scope="{row}">
                <a href="javascript:;" class="coLan"  @click="showWxBox(row)" >{{row.wechatNum}}</a>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" align="center"/>
          <el-table-column show-overflow-tooltip prop="status" label="显示状态" align="center">
            <template slot-scope="{row}">
              {{ row.status === 0 ? '正常' : '禁用' }}
              <el-switch v-if="!isAdmin||btnFunc.some(btn=>btn=='status')" v-model="row.status" :active-value="0"
                :inactive-value="1" size="small" @change="setStatus(row)" />
            </template>
           </el-table-column>
          <el-table-column v-if="isAdmin||(btnFunc.filter(value=>value=='edit'||value=='delete').length>0)" label="操作" width="200" align="center" fixed="right">
            <template slot-scope="scoped">
              <el-row>
              <el-tooltip v-if="isAdmin||btnFunc.some(btn=>btn=='edit')" class="item" effect="dark" content="编辑" placement="bottom">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="channelInfo(scoped.row)"/>
              </el-tooltip>
              </el-row>
            </template>
          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <div  class="page-current">
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            :total="count"
            @current-change="handlePageChange"/>
        </div>
    </el-tabs>

    <!-- 编辑表单 -->
   <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible" :title="dialogTitle+'渠道'">
      <editForm ref="editForm" :infoForm="infoForm"  style="width: 100%" @submit="submit" @closeWin="closeWin"></editForm>
    </el-dialog>

    <!-- 微信 -->
    <el-dialog :close-on-press-escape="false"    :close-on-click-modal="false" center :visible.sync="wxModule" title="微信管理">
      <wxBox ref="wxBox"  @wxAddSuccess='wxAddSuccess' style="width: 100%"  :channelItemData="channelItemData"></wxBox>
    </el-dialog>
  </div>
</template>

<script>

  import channelApi from '@/api/xcx/channel.js'
  import editForm from './edit'
  import wxBox from './wx'
  export default {
    name: "channel",
    data() {
      return {
        wxList:[],
        tableLoading: false,
        // 当前页
        currentPage: 1,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        // 显示编辑角色弹框
        addBtnLoading: false,
        addDialogVisible: false,
        wxModule: false,
        delBtnLoading: false,
        channelItemData:{

        },
        searchParam: {
          mobile: '',
        },
        status: [{
          value: 1,
          label: '正常'
        }, {
          value: 2,
          label: '禁用'
        }],
        channelList: [
          {
            id:1,
            channelNmae:"渠道1",
            wxNub:2,
            creatTime:'2020-10-20'
          }

        ],
        deviceList: [],
        infoForm: {
          name: '',
          status: 1,
          device: 5,
          source: 2,
        },
        loading: false,
        tableHeight: document.body.clientHeight - 245,
        btnFunc: [],
        isAdmin: false,
        dialogTitle: "添加",
      }
    },
    components: {editForm,wxBox},
    created() {
      const {btnFunc, isAdmin} = this.$store.state.user;
      console.log(this.$store.state.user)
      this.btnFunc = btnFunc
      this.isAdmin = isAdmin
      this.pageSize = parseInt((document.body.clientHeight - 344) / 50)
    },
    mounted() {
      // 开启加载动画
      this.tableLoading = true
      // 获取数据列表
      this.getChannelList()
      // 获取参数
      // this.getParamList()
    },
    watch: {
    },
    methods: {
      // 获取微信
      getWxList(id) {
        console.log(this.channelItemData)
        let params = {
          pageIndex: 1,
          pageSize: 1000,
          channel:id
        }
        console.log(params)
        channelApi.channelWxList(params).then(res => {
          this.tableLoading = false;
          console.log(res);
          if (res.code == 200) {
            res.data.records.forEach((item, index) => {
              item.ed = false;
            });
            this.wxList = res.data.records;
            this.tableLoading = true
          }
        }).catch(e => {
          this.tableLoading = false;
        })
      },
      showWxBox(data){
        console.log(data);
          this.wxModule=true;
          this.channelItemData=data.id;

         this.$refs.wxBox&&this.$refs.wxBox.childGetWxList(data.id);
          // this.getWxList(data.id);

      },
      handleSelectionChange(row){
            console.log(row);
      },
      batchDel(){
          console.log(this.$refs.table.clearSelection());
      },
      // 异步获取数据
      async queryData(){
        // 获取设备类型
        await this.getParamList()
      },
      // 初始化搜索条件
      initSearchParam() {
        this.searchParam = {
          mobile: '',
        }
      },
      wxAddSuccess(){
        this.tableLoading = true
        // 获取数据列表
        this.getChannelList();
      },
      // 获取数据列表
      getChannelList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        searchParam.pageIndex = this.currentPage
        searchParam.pageSize = this.pageSize
        channelApi.talkchannel(searchParam).then(res => {
          this.channelList = res.data.records
          this.count = res.data.total
          this.tableLoading = false
        }).catch(e => {
          this.channelList = []
          this.tableLoading = false
        })
      },
      // 获取编辑数据
      channelInfo(data){
        // 初始化表单
        this.initInfoForm()
        // 显示弹窗
        this.addDialogVisible=true
        // 设置标题
        if (data == null) {
          this.dialogTitle = "添加";
        } else {
        this.dialogTitle = "编辑";
        }
        this.$nextTick(function () {
          try {
            console.log(1111);
            channelApi.channelInfo({id: data.id}).then(res => {
              this.infoForm = res.data
              this.$refs.editForm.$refs['infoForm'].resetFields()
            }).catch(e => {
            })
          } catch (e) {

          }
        })
      },
      // 初始化表单
      initInfoForm() {
        this.infoForm = {
         name:''
        }
      },
      // 删除记录
      memberDel(data) {
        this.$confirm('您确定要删除级别吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delBtnLoading = true
          channelApi.memberDel({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            });
            this.delBtnLoading = false
            this.tableLoading = true
            this.getChannelList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 获取参数
      getParamList() {
        channelApi.getParamList().then(res => {
          const {device_list} = res.data
          this.deviceList = device_list ? device_list : {}
        }).catch(e => {
          this.deviceList = {}
        })
      },
      // 设置状态
      setStatus(data) {
        var content = ''
        if (data.status === 0) {
          content = '确定要启用吗？'
        } else {
          content = '确定要禁用吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status,
            id: data.id
          }
          this.tableLoading = true
          channelApi.channelEditor(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getChannelList()
          }).catch(e => {
            let channelList = JSON.parse(JSON.stringify(this.channelList))
            for (let i = 0; i < channelList.length; i++) {
              if (channelList[i].id == data.id) {
                channelList[i].status = data.status == 1 ? 0 : 1
              }
            }
            this.channelList = Object.assign([], channelList)
            this.tableLoading = false
          })
        }).catch(() => {
          let channelList = JSON.parse(JSON.stringify(this.channelList))
          for (let i = 0; i < channelList.length; i++) {
            if (channelList[i].id == data.id) {
              channelList[i].status = data.status == 1 ? 0 : 1
            }
          }
          this.channelList = Object.assign([], channelList)
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        });
      },
      handlePageChange(val) {
        this.currentPage = val
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getChannelList()
      },
      // 搜索
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getChannelList()
      },
      // 提交表单后逻辑处理
      submit(type) {
        if (type == 0) {
          // 添加
          this.search()
        } else {
          // 编辑
          this.tableLoading=true
          this.getChannelList()
          this.$refs.table.bodyWrapper.scrollTop = 0;
          this.addDialogVisible = false
        }
      },
      // 关闭窗体
      closeWin() {
        console.log("关闭")
        // 调用初始化表单方法
        this.initInfoForm()
        // 设置弹窗不可见
        this.addDialogVisible = false
      }
    }
  }
</script>

<style lang="less">
  .coLan{
    color: #1890ff;
  }
  .app-container {
    width: 100%;

    .page-current {
      text-align: center;
      padding: 15px 5px;
      padding-bottom: 0px;

      .sure-page-btn {
        display: inline-block;
        height: 28px;
        line-height: 0;
        width: 46px;
        padding: 0;
        vertical-align: top;
      }
    }
  }

</style>
